import Vue from 'vue'
import vueRouter from 'vue-router'
import routes from './routes.js'
import { isLogin } from '../utils/auth'


Vue.use(vueRouter)

// //解决编程式路由往同一地址跳转时会报错的情况
// var originalPush = vueRouter.prototype.push;
// var originalReplace = vueRouter.prototype.replace;
// //push
// vueRouter.prototype.push = function push(location, onResolve, onReject) {
//   if (onResolve || onReject)
//     return originalPush.call(this, location, onResolve, onReject);
//   return originalPush.call(this, location).catch(err => err);
// };
// //replace
// vueRouter.prototype.replace = function push(location, onResolve, onReject) {
//   if (onResolve || onReject)
//     return originalReplace.call(this, location, onResolve, onReject);
//   return originalReplace.call(this, location).catch(err => err);
// };

//解决编程式路由往同一地址跳转时会报错的情况
const originalPush = vueRouter.prototype.push

vueRouter.prototype.push = function push(location) {

    return originalPush.call(this, location).catch(err => err)

}


let router = new vueRouter({

    mode: 'history',
    routes
});

//用户判断登录跳转
router.beforeEach((to, from, next) => {
    let isAuth = isLogin();
    if (to.path == '/login' || to.path == '/admin') {
        if (isAuth) {
            next('/');
        } else {
            next();
        }
    } else {
        if (isAuth) {
            next();
        } else {
            next('/login');
        }
    }
    //用户去admin直接跳转到backstage
    // if(to.path=='/admin'){
    //     if(isAuth){
    //         next('/backstage');
    //     }else{
    //         next();
    //     }
    // }else{
    //     if(isAuth){
    //         next();
    //     }else{
    //         next('/admin');
    //     }
    // }
})


router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth)//判断该路由是否需要登录权限
    {
        if (localStorage.getItem("token") === 'true')//判断本地是否存在token
        {
            next();
        }
        else {
            next({
                path: '/'
            })
        }
    }
    else {
        if (localStorage.getItem("token") === 'true') {
            next()
        }
        else {
            next();
        }
    }
    next();
})


export default router;